package any.util;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import any.impl.SimpleTypeAnything;


public final class TypeRegistry {

	private static final Set<SimpleTypeAnyCreator> registry = new LinkedHashSet<SimpleTypeAnyCreator>();

	public void simpleTypeCreator(SimpleTypeAnyCreator creator) throws NullPointerException {
		if (creator == null)
			throw new NullPointerException();

		synchronized (registry) {
			registry.add(creator);
		}
	}

	public SimpleTypeAnything<?> getAnyFor(Object obj) {
		SimpleTypeAnyCreator creatorCandidate = null;
		synchronized (registry) {
			Priority highestPrio = Priority.LOW;
			for (SimpleTypeAnyCreator creator : registry) {
				int compared = creator.priority().compareTo(highestPrio);
				if ((compared > 0 || (compared == 0 && creatorCandidate == null))
				        && creator.canCreateFrom(obj)) {
					creatorCandidate = creator;
					if (highestPrio == Priority.HIGH) 
						break;
				}
			}
		}

		return (creatorCandidate != null ? creatorCandidate.createFrom(obj) : null);
	}

	public SimpleTypeAnything<?> parse(String str) {
		List<SimpleTypeAnything<?>> candidates = new ArrayList<SimpleTypeAnything<?>>();
		for (SimpleTypeAnyCreator creator : registry) {
	        SimpleTypeAnything<?> any = creator.parse(str);
        }
		
		return null;
	}

	public enum Priority {
		LOW, DEFAULT, HIGH;

		public boolean isHigherOrEqualTo(Priority prio) throws NullPointerException {
			return compareTo(prio) >= 0;
		}
	}

	public interface SimpleTypeAnyCreator {

		Priority priority();

		boolean canCreateFrom(Object obj);

		SimpleTypeAnything<?> createFrom(Object obj);

		SimpleTypeAnything<?> parse(String str);
	}

}
